import type { Request, Response, NextFunction } from "express";
import { fileURLToPath } from "url";
import { resolve, dirname, join } from "path"
import fs from 'fs-extra'

export function catchAsync(fn: Function) {
  return (req: Request, res: Response, next: NextFunction) => {
    fn(req, res, next).catch((err: Error) => next(err))
  }
};

export function randomChars(len: number): string {
  const result: string[] = [];

  for (let i = 0; i < len; i++) {
    // 生成0~25的随机数字
    const ram = Math.ceil(Math.random() * 25);
    // 获取大写字母（A~Z的ASCII码65-90）
    const char = String.fromCharCode(65 + ram);
    // 随机转为大小
    result.push(Math.random() > 0.5 ? char.toLowerCase() : char);
  }

  return result.join('');
}

export function getClientIp(req: Request): string {
  const originIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress || ""
  const matches = (originIp as string).match(/:(\d[\w\W]+)/) || []
  return matches[1] || ""
};

export function getFileSuffix(filename: string): string {
  const REGX = /\.([^.]+)$/
  const matches = filename.match(REGX) || []
  return matches[1] || ""
}

export function getFilePrefix(filename: string): string {
  const REGX = /([\w\W]+)(?=\.)/
  const matches = filename.match(REGX) || []
  return matches[1] || filename
}

export function getPathFromDir(path: string): string {
  const rootDir = resolve(dirname(fileURLToPath(import.meta.url)), "../")
  return join(rootDir, path)
}

export function getPathFromRoot(path: string): string {
  return join(process.cwd(), path)
}

export function formatTime(time: number) {
  let date = new Date(time); // 初始化日期
  let year = date.getFullYear(); //获取年份
  let month = date.getMonth() + 1; // 获取月份
  let day = date.getDate(); // 获取具体日
  let hour = date.getHours(); // 获取时
  let minutes = date.getMinutes(); // 获取分
  let seconds = date.getSeconds(); // 获取秒
  return year + '-' + month + '-' + day + '-' + hour + '-' + minutes + '-' + seconds
}

export function modifyFileName(oldName: string, newName: string) {
  fs.rename(oldName, newName, err => { if (err) throw err });
}
